﻿using Iworld.Administrator.Model;
using Iworld.basis.Service;
using Iworld.Basis.Help;
using Iworld.Basis.Manager;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace Iworld.Administrator.Service.Import
{
    /// <summary>
    /// 创建管理员的数据集
    /// </summary>
     [DataContract]
    public class CreateAdministratorImport : CheckAdministratorImportBase, IPackageForCreateModel<IModelToDbContextOfAdministrator,
         Iworld.Administrator.Model.Administrator>
    {
        #region 属性

        /// <summary>
        /// 账号
        /// </summary>
        [DataMember]
        public string Account { get; set; }

         /// <summary>
         /// 用户名
         /// </summary>
        [DataMember]
        public string Username { get; set; }

        /// <summary>
        /// 密码
        /// </summary>
        [DataMember]
        public string Password { get; set; }

        /// <summary>
        /// 所从属的管理员组的存储指针
        /// </summary>
        [DataMember]
        public int GroupId { get; set; }

        #endregion

        public override void CheckAllowExecuteOrNot(Main.Impl.ModelToDbContext db)
        {
            base.CheckAllowExecuteOrNot(db);
            if (!Self.Group.CanEditAdministrator)
            {
                throw new Exception("你无权修改或添加管理员");
            }

        }


        public void CheckData(IModelToDbContextOfAdministrator db)
        {
            #region 检查用户名和密码格式是否合法
            this.Account = VerifyHelper.EliminateSpaces(this.Account);
            this.Password = VerifyHelper.EliminateSpaces(this.Password);
            VerifyHelper.Check(this.Account, VerifyHelper.Key.Nickname);
            VerifyHelper.Check(this.Password, VerifyHelper.Key.Password);
            #endregion
            bool hadUsedUsername = db.Administrators.Any(x => x.Account == this.Account);
            if (hadUsedUsername)
            {
                string error = string.Format("账号 {0} 已经被使用", this.Account);
                throw new Exception(error);
            }
        }

        public Model.Administrator GetModel(IModelToDbContextOfAdministrator db)
        {
            AdministratorGroup group = db.AdministratorGroups.Find(this.GroupId);
            if (group == null) throw new Exception("管理员组不存在");
            string password = EncryptHelper.EncryptByMd5(this.Password);
            return new Model.Administrator() { Account = this.Account, Username = this.Username, Password = password,Group = group };
        }
    }
}
